// pages/preference/preference.js
let selectPronvice = '';
const { HTTP } = require('../../utils/http');
const { api } = require('../../utils/api');
const { request } = new HTTP();
let selectCity = {};
// 获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    sex: '',
    position: '',
    hobby: {
      rangeValuesHeight: [150, 200],
      rangeValuesAge: [18, 30],
    },
    eduList: [],
    one: false,
    two: false,
    three: false,
    fort: false,
    five: false,
    loading: false,
    cityList: [
      {
        values: [],
        className: 'column1'
      },
      {
        values: [],
        className: 'column2',
      }
    ],
    xzList: [
      {
        values: [
          {value: '水瓶座', name: '水瓶座'},
          {value: '双鱼座', name: '双鱼座'},
          {value: '白羊座', name: '白羊座'},
          {value: '金牛座', name: '金牛座'},
          {value: '双子座', name: '双子座'},
          {value: '巨解座', name: '巨解座'},
          {value: '狮子座', name: '狮子座'},
          {value: '处女座', name: '处女座'},
          {value: '天秤座', name: '天秤座'},
          {value: '天蝎座', name: '天蝎座'},
          {value: '射手座', name: '射手座'},
          {value: '摩羯座', name: '摩羯座'},
        ],
        className: 'column1'
      },
    ],
    cityShow: false,
    xzShow: false,
    userInfo: {
      province_id: '',
      city_id: ''
    },
    currentCity: {
      index: [0, 0],
      value: ['北京', '北京']
    },
    currentXz: {
      index: [0],
      value: ['']
    },
    hometown: {
      one: '+',
      two: '+',
      three: '+',
    },
    xingZuo: {
      one: '+',
      two: '+',
      three: '+',
    },
    hometownKey: '',
    xingZuoKey: '',
    appInfo: {}
  },

  onRangeChange(e) {
    let { detail: {minValue, maxValue} } = e;
    this.setData({
      'hobby.rangeValuesHeight': [Math.round(minValue), Math.round(maxValue)]
    });
  },
  onRangeChangeAge(e) {
    let { detail: {minValue, maxValue} } = e;
    this.setData({
      'hobby.rangeValuesAge': [Math.round(minValue), Math.round(maxValue)]
    });
  },
  oncityShowClose() {
    this.setData({cityShow: false});
  },
  onxzShowClose() {
    this.setData({xzShow: false})
  },
  slectCity(e) {
    this.setData({cityShow: true, hometownKey: e.target.dataset.key});
  },
  slectXingZuo(e) {
    this.setData({ xzShow: true ,xingZuoKey: e.target.dataset.key})
  },
  cityConfirm(e) {
    const {value, index} = e.detail;
    this.setData({
      'currentCity': {
        value,
        index
      },
      cityShow: false
    })
    let key = this.data.hometownKey
    const hKey = `hometown.${key}`;
    this.setData({
      [hKey]: this.data.currentCity.value[1].name
    });
  },
  xzConfirm(e) {
    const {value, index} = e.detail;
    console.log(e.detail)
    this.setData({
      'currentXz': {
        value,
        index
      },
      xzShow: false
    })
    console.log(this.data.currentXz)
    let key = this.data.xingZuoKey
    const hKey = `xingZuo.${key}`;
    this.setData({
      [hKey]: this.data.currentXz.value[0].name
    });
  },
  // 初始化地址
  _initAddress() {
    const pronviceIndex = this.data.cityList[0].values.findIndex(item => item.code == this.data.userInfo.province_id);
    const cityIndex = this.data.cityList[1].values.findIndex(item => item.code == this.data.userInfo.city_id);
    this.setData({
      'currentCity.index': [pronviceIndex, cityIndex],
      'currentCity.value': [this.data.userInfo.province, this.data.userInfo.city],
    })
    const cityPicker = this.selectComponent('.cityPicker');
    cityPicker.setIndexes([pronviceIndex, cityIndex]);
  },
  onXzChange(e) {
    const {value, index} = e.detail;
  },
  slecteSex(e) {
    let sex =  e.target.dataset.sex
    this.setData({
      sex: sex
    })
  },
  selcteEdu(e) {
    let key = e.target.dataset.key
    console.log('---key-')
    console.log(key)
    let eduList = this.data.eduList
    let index = eduList.indexOf(key)
    if(index > -1) {
      eduList.splice(index,1)
    }else {
      eduList.push(key)
    }
    this.setData({eduList: eduList}, function() {
      // 设置是否选中
      if(this.data.eduList.indexOf("1") > -1) {
        this.setData({one: true})
      }else{
        this.setData({one: false})
      }
      if(this.data.eduList.indexOf("2") > -1) {
        this.setData({two: true})
      }else{
        this.setData({two: false})
      }
      if(this.data.eduList.indexOf("3") > -1) {
        this.setData({three: true})
      }else{
        this.setData({three: false})
      }
      if(this.data.eduList.indexOf("4") > -1) {
        this.setData({fort: true})
      }else{
        this.setData({fort: false})
      }
      if(this.data.eduList.indexOf("5") > -1) {
        this.setData({five: true})
      }else{
        this.setData({five: false})
      }
    })

  


    // this.setData({eduList: eduList})
    console.log('---eduList-')
    console.log(this.data.eduList)
  },
  // 保存
  saveBtn() {
    let xzStr = []
    let htStr = []
    for(let key in this.data.xingZuo) {
      if(this.data.xingZuo[key] !== '+') {
        xzStr.push(this.data.xingZuo[key])
      }
    }
    for(let key in this.data.hometown) {
      if(this.data.hometown[key] !== '+') {
        htStr.push(this.data.hometown[key])
      }
    }

    let data = {
      sex: this.data.sex,
      position: this.data.position,
      minAge: this.data.hobby.rangeValuesAge[0],
      maxAge: this.data.hobby.rangeValuesAge[1],
      minHeight: this.data.hobby.rangeValuesHeight[0],
      maxHeight: this.data.hobby.rangeValuesHeight[1],
      educationLevel: this.data.eduList.join(','),
      province: htStr.join(','),
      constellation: xzStr.join(','),
      longitude: '112.33',
      latitude: '33.88'
    }
    this._postMarrayLike(data)
  },
    // 城市
    onCityChange(event) {
      const { picker, value, index } = event.detail;
      console.log('--onCityChange--')
      console.log(event.detail)
      if (selectCity.code && value[0].code == selectCity.code) {
        return;
      }
      selectCity = value[0];
      this._getCitys(value[0].code, (citys) => {
        picker.setColumnValues(1, citys);
      });
    },
    showVip() {
      wx.showToast({
        title: '请开通vip',
        icon: 'none'
      })
    },
     // 获取省份信息
    async _getProvinces() {
      const {returnCode = '', beans = []} = await request({
        url: api.getProvinces,
        method: 'get',
        data: {}
      });
      if (returnCode === '0000') {
        const key = `cityList[${0}].values`
        this.setData({
          [key]: beans
        });
        this._getCitys(this.data.userInfo.province_id || 101010000, () => {}, true);
      }
    },
    // 获取城市
    async _getCitys(provinceCode, cb, isFirst = false) {
      this.setData({ loading: true });
      const {returnCode = '', beans = []} = await request({
        url: api.getCitys,
        method: 'get',
        data: {provinceCode}
      });
      this.setData({ loading: false });
      if (returnCode === '0000') {
        const key = `cityList[${1}].values`
        this.setData({
          [key]: beans
        });
        cb && cb(beans);

        isFirst && this._initAddress();
      }
    },

    // 获取匹配设置
    async _marrayLike() {
      const {returnCode = '', bean = {}} = await request({
        url: api.marray_like,
        method: 'get',
        data: {}
      });
      if (returnCode === '0000') {

        let eArr = (bean.educationLevel + '').split(',')
        let consArr = (bean.constellation + '').split(',')
        let pArr = (bean.province + '').split(',')
        if(consArr.length == 1) {
          this.setData({
            'xingZuo.one': consArr[0]
          });
        }
        if(consArr.length == 2) {
          this.setData({
            'xingZuo.one': consArr[0],
            'xingZuo.two': consArr[1]
          });
        }
        if(consArr.length == 3) {
          this.setData({
            'xingZuo.one': consArr[0],
            'xingZuo.two': consArr[1],
            'xingZuo.three': consArr[2]
          });
        }

        if(pArr.length == 1) {
          this.setData({
            'hometown.one': pArr[0]
          });
        }
        if(pArr.length == 2) {
          this.setData({
            'hometown.one': pArr[0],
            'hometown.two': pArr[1]
          });
        }
        if(pArr.length == 3) {
          this.setData({
            'hometown.one': pArr[0],
            'hometown.two': pArr[1],
            'hometown.three': pArr[2]
          });
        }


       this.setData({
        eduList: eArr,
        // pipeiData: bean
        sex: bean.sex,
        position: bean.position,
        'hobby.rangeValuesHeight': [bean.minHeight || 130,  bean.maxHeight || 130],
        'hobby.rangeValuesAge': [bean.minAge || 16,  bean.maxAge || 16]
       }, function() {
          if(this.data.eduList.indexOf("1") > -1) {
            this.setData({one: true})
          }else{
            this.setData({one: false})
          }
          if(this.data.eduList.indexOf("2") > -1) {
            this.setData({two: true})
          }else{
            this.setData({two: false})
          }
          if(this.data.eduList.indexOf("3") > -1) {
            this.setData({three: true})
          }else{
            this.setData({three: false})
          }
          if(this.data.eduList.indexOf("4") > -1) {
            this.setData({fort: true})
          }else{
            this.setData({fort: false})
          }
          if(this.data.eduList.indexOf("5") > -1) {
            this.setData({five: true})
          }else{
            this.setData({five: false})
          }
        }
       )
      }
    },
    // 更改保存匹配设置
    async _postMarrayLike(pars) {
      const {returnCode = '', bean = {}, returnMessage = ''} = await request({
        url: api.marray_like,
        method: 'put',
        data: pars
      });
      if (returnCode === '0000') {
        wx.showToast({
          title: '设置成功',
        })
        wx.navigateBack({
          delta: 1
        });
        
      } else{
        wx.showToast({
          title: returnMessage,
        })
      }
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getProvinces()
    this._marrayLike()
    this.setData({
      appInfo: app.globalData.userInfo 
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})